<template>
  <div class="event-trigger-panel">
    <a-card title="事件触发器管理" :bordered="false">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showCreateModal">
            <template #icon>
              <IconifyIcon icon="ant-design:plus-outlined" />
            </template>
            新建触发器
          </a-button>
          <a-button @click="refreshData">
            <template #icon>
              <IconifyIcon icon="ant-design:reload-outlined" />
            </template>
            刷新
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="triggers"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'triggerType'">
            <a-tag :color="getTriggerTypeColor(record.triggerType)">
              {{ getTriggerTypeLabel(record.triggerType) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'enabled'">
            <a-switch
              :checked="record.enabled"
              @change="(checked) => handleToggleEnabled(record.id, checked)"
            />
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="showEditModal(record)">
                编辑
              </a-button>
              <a-button type="link" size="small" @click="handleTest(record)">
                测试
              </a-button>
              <a-popconfirm
                title="确定要删除这个触发器吗？"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑触发器模态框 -->
    <a-modal
      :open="modalVisible"
      :title="editingTrigger ? '编辑事件触发器' : '新建事件触发器'"
      width="800px"
      @ok="handleSave"
      @cancel="closeModal"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="触发器名称" name="name">
              <a-input
                v-model:value="formData.name"
                placeholder="请输入触发器名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="触发器类型" name="triggerType">
              <a-select
                v-model:value="formData.triggerType"
                placeholder="请选择触发器类型"
              >
                <a-select-option value="SCHEDULE">定时触发</a-select-option>
                <a-select-option value="CONDITION">条件触发</a-select-option>
                <a-select-option value="MANUAL">手动触发</a-select-option>
                <a-select-option value="WEBHOOK">Webhook触发</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="触发条件" name="triggerCondition">
          <a-textarea
            v-model:value="formData.triggerCondition"
            placeholder="请输入触发条件"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="目标事件" name="targetEvent">
          <a-input
            v-model:value="formData.targetEvent"
            placeholder="请输入目标事件名称"
          />
        </a-form-item>

        <a-form-item label="启用状态" name="enabled">
          <a-switch v-model:checked="formData.enabled" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import type { FormInstance } from 'ant-design-vue';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'trigger-created': [trigger: any];
  'trigger-updated': [trigger: any];
}>();

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const editingTrigger = ref<any>(null);
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive({
  name: '',
  triggerType: '',
  triggerCondition: '',
  targetEvent: '',
  enabled: true,
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入触发器名称' }],
  triggerType: [{ required: true, message: '请选择触发器类型' }],
  targetEvent: [{ required: true, message: '请输入目标事件名称' }],
};

// 模拟数据
const triggers = ref([
  {
    id: '1',
    name: '每日备份触发器',
    triggerType: 'SCHEDULE',
    triggerCondition: '0 2 * * *',
    targetEvent: 'backup_event',
    status: 'ACTIVE',
    enabled: true,
  },
  {
    id: '2',
    name: '资源状态监控触发器',
    triggerType: 'CONDITION',
    triggerCondition: 'resource.status === "ERROR"',
    targetEvent: 'alert_event',
    status: 'ACTIVE',
    enabled: true,
  },
  {
    id: '3',
    name: '手动维护触发器',
    triggerType: 'MANUAL',
    triggerCondition: '',
    targetEvent: 'maintenance_event',
    status: 'INACTIVE',
    enabled: false,
  },
]);

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列配置
const columns = [
  {
    title: '触发器名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '触发器类型',
    dataIndex: 'triggerType',
    key: 'triggerType',
    width: 120,
  },
  {
    title: '触发条件',
    dataIndex: 'triggerCondition',
    key: 'triggerCondition',
    ellipsis: true,
  },
  {
    title: '目标事件',
    dataIndex: 'targetEvent',
    key: 'targetEvent',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '启用状态',
    dataIndex: 'enabled',
    key: 'enabled',
    width: 100,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 方法
const loadData = () => {
  loading.value = true;
  setTimeout(() => {
    pagination.value.total = triggers.value.length;
    loading.value = false;
  }, 500);
};

const refreshData = () => {
  loadData();
  message.success('数据刷新成功');
};

const showCreateModal = () => {
  editingTrigger.value = null;
  resetFormData();
  modalVisible.value = true;
};

const showEditModal = (record: any) => {
  editingTrigger.value = record;
  Object.assign(formData, record);
  modalVisible.value = true;
};

const closeModal = () => {
  modalVisible.value = false;
  resetFormData();
};

const resetFormData = () => {
  Object.assign(formData, {
    name: '',
    triggerType: '',
    triggerCondition: '',
    targetEvent: '',
    enabled: true,
  });
  formRef.value?.clearValidate();
};

const handleSave = async () => {
  try {
    await formRef.value?.validate();

    if (editingTrigger.value) {
      const index = triggers.value.findIndex(
        (item) => item.id === editingTrigger.value.id,
      );
      if (index !== -1) {
        triggers.value[index] = {
          ...editingTrigger.value,
          ...formData,
        };
      }
      message.success('事件触发器更新成功');
      emit('trigger-updated', formData);
    } else {
      const newTrigger = {
        id: Date.now().toString(),
        ...formData,
        status: 'ACTIVE',
      };
      triggers.value.unshift(newTrigger);
      message.success('事件触发器创建成功');
      emit('trigger-created', newTrigger);
    }

    closeModal();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleDelete = (id: string) => {
  const index = triggers.value.findIndex((item) => item.id === id);
  if (index !== -1) {
    triggers.value.splice(index, 1);
    message.success('事件触发器删除成功');
  }
};

const handleToggleEnabled = (id: string, enabled: boolean) => {
  const trigger = triggers.value.find((item) => item.id === id);
  if (trigger) {
    trigger.enabled = enabled;
    message.success(`事件触发器已${enabled ? '启用' : '禁用'}`);
  }
};

const handleTest = (record: any) => {
  message.success(`触发器 ${record.name} 测试功能开发中...`);
};

const getTriggerTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    SCHEDULE: '定时触发',
    CONDITION: '条件触发',
    MANUAL: '手动触发',
    WEBHOOK: 'Webhook触发',
  };
  return typeMap[type] || type;
};

const getTriggerTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    SCHEDULE: 'blue',
    CONDITION: 'green',
    MANUAL: 'orange',
    WEBHOOK: 'purple',
  };
  return colorMap[type] || 'default';
};

const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '活跃',
    INACTIVE: '非活跃',
    ERROR: '错误',
  };
  return statusMap[status] || status;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    ACTIVE: 'green',
    INACTIVE: 'default',
    ERROR: 'red',
  };
  return colorMap[status] || 'default';
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.event-trigger-panel {
  // 样式可以根据需要添加
}
</style>
